<template>
  <div class="">
    <el-upload
      :class="{ disabled: disabledComputed }"
      list-type="picture-card"
      action="#"
      :file-list="fileList"
      :limit="1"
      :on-preview="preview"
      :on-remove="handleRemove"
      :on-change="onChange"
      :before-upload="beforeUpload"
      :http-request="onUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="showProgress" :percentage="percent" style="width: 180px;" />
    <el-dialog title="图片预览" :visible.sync="showdialog" width="30%">
      <img :src="previewUrl" style="width: 100%">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDLTKyPbiAWe4A0Yhpbx4h57vCLq5D3sQT',
  SecretKey: 'ynPkGI90aOl3QatzykLlynOmvSGqC0oo'
})
export default {
  name: 'ImageUpload',
  components: {},
  props: {},
  data() {
    return {
      fileList: [],
      showdialog: false,
      previewUrl: '',
      currentFileUid: null, // 存储上传文件的uid
      showProgress: false,
      percent: 0
    }
  },
  computed: {
    disabledComputed() {
      return this.fileList.length === 1
    }
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    preview(file) {
      this.showdialog = true
      this.previewUrl = file.url
    },
    handleRemove(file) {
      // 方式1
      const index = this.fileList.findIndex(t => t.url === file.url)
      this.fileList.splice(index, 1)
      // 方式2
      // this.fileList = []
    },
    // 这个方法会触发两次 -> 添加图片/上传成功或失败
    onChange(file, fileList) {
      // 方式1
      // if (!this.fileList.some(item => item.uid === file.uid)) {
      //   this.fileList.push(file)
      //   this.fileList.status = 'success'
      // }
      // 方式2
      this.fileList = fileList.map(item => item)
    },
    beforeUpload(file) {
      if (!['image/jpeg', 'image/gif', 'image/bmp', 'image/png'].includes(file.type)) {
        this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      if (file.size > 5 * 1024 * 1024) {
        this.$message.error('图片大小不能超过5M')
        return false
      }
      this.currentFileUid = file.uid
      this.showProgress = true
      return true
    },
    onUpload(params) {
      if (params.file) {
        cos.putObject({
          Bucket: 'hrsaas-1305602511', /* 必须 */
          Region: 'ap-chengdu', /* 存储桶所在地域，必须字段 */
          Key: params.file.name, /* 必须 */
          StorageClass: 'STANDARD',
          Body: params.file, // 上传文件对象
          onProgress: progressData => {
            // console.log(JSON.stringify(progressData))
            console.log(progressData.percent)
            this.percent = progressData.percent * 100
          }
        }, (err, data) => {
          // console.log(err || data)
          this.showProgress = false
          if (!err && data.statusCode === 200) {
            /* 主要考虑数据响应式问题 */
            // 方式1
            // this.fileList = this.fileList.map(t => {
            //   if (t.uid === this.currentFileUid) {
            //     return { url: 'http://' + data.Location, upload: true }
            //   }
            // })
            // 方式2
            this.$set(this.fileList, 0, { url: 'http://' + data.Location, upload: true })
            // 方式3
            // this.fileList.push({ url: 'http://' + data.Location, upload: true })
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .disabled .el-upload--picture-card {
  display: none;
}
</style>
